﻿using System.Globalization;
using System.Text;
using Compiler.Entities;
using Core.AbstractEntities;

namespace Operations.Entities
{
    /// <summary>
    /// Execution of the operation
    /// </summary>
    public class OperationList : Operation
    {
        /// <summary>
        /// Constructor by default
        /// </summary>
        public OperationList(HpCollection hpCollection)
        {
            this.HpCollection = hpCollection;
        }
        /// <summary>
        /// Return the result of the operation
        /// {4 6 8}  3  +  i.e {12 18 24}
        /// {5 7 9}  2  *  i.e {10 14 18}
        /// </summary>
        public override HpElement Execute()
        {
            HpElement operatorItem = HpCollection.Get(HpCollection.Count - 1);
            HpElement element1 = HpCollection.Get(HpCollection.Count - 2);
            HpElement elementList = HpCollection.Get(HpCollection.Count - 3);
            StringBuilder resultItems = new StringBuilder();

            string[] items;
            elementList.Value = elementList.Value.ToString().Replace("{", string.Empty).Replace("}", string.Empty);
            items = elementList.Value.ToString().Split(' ');

            string template = @"
                        using System;
                        public class Calculator
                        {{
                          public static object Execute()
                          {{ 
                           {0} o1 = {1};
                           {2} o2 = {3};
                           return o2{4}o1;
                          }}
                        }}";

            string code;
            resultItems.Append("{");

            foreach (var item in items)
            {
                code = string.Empty;
                code = string.Format(new CultureInfo("en-US"),
                        template,
                        element1.Type.ToString(),
                        element1.Value.ToString().Replace(',', '.'),
                        "System.Double",
                        item.Replace(',', '.'),
                        operatorItem.Value.ToString());

                resultItems.Append(Program.Execute(code));
                resultItems.Append(" ");
            }
            resultItems.Remove(resultItems.Length - 1, 1);
            resultItems.Append("}");


            HpElement newElement = new HpElement()
            {
                Type = resultItems.GetType(),
                Value = resultItems.ToString()
            };

            return newElement;
        }
    }
}
